<template>
  <view class="page">
    <!-- 商品图片 -->
    <view class="product-image-section">
      <image 
        class="product-image" 
        :src="productImage" 
        mode="aspectFill"
        @error="handleImageError"
      ></image>
      <view class="product-badge" v-if="product.sales > 100">🔥 热销</view>
    </view>

    <!-- 商品信息 -->
    <view class="product-info-section">
      <view class="product-header">
        <text class="product-name">{{ product.name }}</text>
        <view class="product-tags">
          <text class="tag-stock" v-if="product.stock < 10 && product.stock > 0">
            仅剩{{ product.stock }}件
          </text>
          <text class="tag-out" v-if="product.stock === 0">已售罄</text>
        </view>
      </view>
      
      <view class="product-price-row">
        <view class="price-box">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{ product.price }}</text>
          <text class="price-original" v-if="product.originalPrice">
            ¥{{ product.originalPrice }}
          </text>
        </view>
        <view class="sales-info">
          已售 {{ product.sales || 0 }}
        </view>
      </view>

      <view class="product-desc" v-if="product.description">
        <text class="desc-title">商品描述</text>
        <text class="desc-content">{{ product.description }}</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="quantity-control">
        <text class="label">数量</text>
        <view class="control-group">
          <view 
            class="btn-minus" 
            :class="{ disabled: quantity <= 1 }"
            @click="decreaseQuantity"
          >-</view>
          <input 
            class="quantity-input" 
            type="number" 
            v-model="quantity"
            @blur="validateQuantity"
          />
          <view 
            class="btn-plus" 
            :class="{ disabled: quantity >= maxQuantity }"
            @click="increaseQuantity"
          >+</view>
        </view>
      </view>
      
      <view class="action-buttons">
        <view class="btn-cart" @click="addToCart">
          <text class="btn-icon">🛒</text>
          <text class="btn-text">加入购物车</text>
        </view>
        <view class="btn-buy" @click="buyNow">
          <text class="btn-text">立即购买</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getProductImage, handleImageError } from '@/utils/image'

export default {
  data() {
    return {
      productId: null,
      product: {},
      quantity: 1,
      loading: false,
      imageError: false
    }
  },
  computed: {
    maxQuantity() {
      // 最大购买数量：库存或99，取最小值
      return Math.min(this.product.stock || 99, 99)
    },
    productImage() {
      // 如果图片加载失败，使用默认图片
      if (this.imageError) {
        return handleImageError('product')
      }
      // 否则使用商品图片（包含默认处理）
      return getProductImage(this.product.image)
    }
  },
  onLoad(options) {
    if (options.id) {
      this.productId = options.id
      this.loadProductDetail()
    }
  },
  methods: {
    async loadProductDetail() {
      if (this.loading) return
      this.loading = true
      
      try {
        const { getProductDetail } = require('@/api/product')
        const product = await getProductDetail(this.productId)
        this.product = product
        // 重置图片错误状态
        this.imageError = false
        
        //console.log('商品详情:', product)
      } catch (error) {
        console.error('加载商品详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        
        // 延迟返回
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } finally {
        this.loading = false
      }
    },
    
    handleImageError(e) {
      //console.log('图片加载失败:', e)
      this.imageError = true
    },
    
    increaseQuantity() {
      if (this.quantity < this.maxQuantity) {
        this.quantity++
      }
    },
    
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    
    validateQuantity() {
      let num = parseInt(this.quantity)
      if (isNaN(num) || num < 1) {
        num = 1
      } else if (num > this.maxQuantity) {
        num = this.maxQuantity
      }
      this.quantity = num
    },
    
    addToCart() {
      // 校验
      if (!this.product.id) {
        uni.showToast({ title: '商品信息错误', icon: 'none' })
        return
      }
      
      if (this.product.stock === 0) {
        uni.showToast({ title: '商品已售罄', icon: 'none' })
        return
      }
      
      if (this.product.status !== 1) {
        uni.showToast({ title: '商品已下架', icon: 'none' })
        return
      }
      
      // 获取购物车
      let cart = uni.getStorageSync('cart') || []
      
      // 查找是否已存在
      const index = cart.findIndex(item => item.productId === this.product.id)
      
      if (index > -1) {
        // 已存在，增加数量
        const newQuantity = cart[index].quantity + this.quantity
        if (newQuantity > this.maxQuantity) {
          uni.showToast({
            title: `最多只能购买${this.maxQuantity}件`,
            icon: 'none'
          })
          return
        }
        cart[index].quantity = newQuantity
      } else {
        // 不存在，添加新商品
        cart.push({
          productId: this.product.id,
          name: this.product.name,
          image: this.product.image,
          price: this.product.price,
          quantity: this.quantity,
          stock: this.product.stock,
          selected: true
        })
      }
      
      // 保存购物车
      uni.setStorageSync('cart', cart)
      
      // 更新购物车数量
      const totalCount = cart.reduce((sum, item) => sum + item.quantity, 0)
      uni.setStorageSync('cartCount', totalCount)
      
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      })
      
      // 重置数量
      this.quantity = 1
    },
    
    buyNow() {
      // 校验
      if (!this.product.id) {
        uni.showToast({ title: '商品信息错误', icon: 'none' })
        return
      }
      
      if (this.product.stock === 0) {
        uni.showToast({ title: '商品已售罄', icon: 'none' })
        return
      }
      
      if (this.product.status !== 1) {
        uni.showToast({ title: '商品已下架', icon: 'none' })
        return
      }
      
      // 构建订单商品数据
      const items = [{
        productId: this.product.id,
        name: this.product.name,
        image: this.product.image,
        price: this.product.price,
        quantity: this.quantity
      }]
      
      // 跳转到订单确认页
      uni.navigateTo({
        url: '/pages/order/confirm?from=detail&items=' + encodeURIComponent(JSON.stringify(items))
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 180rpx;
}

/* 商品图片区 */
.product-image-section {
  position: relative;
  width: 100%;
  height: 750rpx;
  background: #fff;
  
  .product-image {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }
  
  .product-badge {
    position: absolute;
    top: 32rpx;
    right: 32rpx;
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
    color: #fff;
    font-size: 24rpx;
    padding: 12rpx 24rpx;
    border-radius: 40rpx;
    box-shadow: 0 4rpx 12rpx rgba(255, 154, 158, 0.4);
  }
}

/* 商品信息区 */
.product-info-section {
  background: #fff;
  margin-top: 20rpx;
  padding: 32rpx;
}

.product-header {
  margin-bottom: 24rpx;
  
  .product-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    line-height: 1.5;
    display: block;
    margin-bottom: 16rpx;
  }
}

.product-tags {
  display: flex;
  gap: 16rpx;
  
  .tag-stock {
    background: #fff3e0;
    color: #ff9800;
    font-size: 22rpx;
    padding: 8rpx 16rpx;
    border-radius: 8rpx;
  }
  
  .tag-out {
    background: #f5f5f5;
    color: #999;
    font-size: 22rpx;
    padding: 8rpx 16rpx;
    border-radius: 8rpx;
  }
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  .price-box {
    display: flex;
    align-items: baseline;
    gap: 8rpx;
    
    .price-symbol {
      font-size: 28rpx;
      color: #ff4d4f;
      font-weight: bold;
    }
    
    .price-value {
      font-size: 48rpx;
      color: #ff4d4f;
      font-weight: bold;
    }
    
    .price-original {
      font-size: 24rpx;
      color: #999;
      text-decoration: line-through;
    }
  }
  
  .sales-info {
    font-size: 24rpx;
    color: #999;
  }
}

.product-desc {
  margin-top: 32rpx;
  
  .desc-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .desc-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.8;
    display: block;
  }
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
  
  .label {
    font-size: 28rpx;
    color: #333;
  }
  
  .control-group {
    display: flex;
    align-items: center;
    gap: 24rpx;
    
    .btn-minus,
    .btn-plus {
      width: 56rpx;
      height: 56rpx;
      border: 2rpx solid #ddd;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;
      
      &.disabled {
        opacity: 0.3;
      }
    }
    
    .quantity-input {
      width: 100rpx;
      height: 56rpx;
      text-align: center;
      font-size: 28rpx;
      border: 2rpx solid #ddd;
      border-radius: 8rpx;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 24rpx;
  
  .btn-cart,
  .btn-buy {
    flex: 1;
    height: 88rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
  }
  
  .btn-cart {
    background: linear-gradient(135deg, #ffa726 0%, #fb8c00 100%);
    
    .btn-icon {
      font-size: 36rpx;
    }
    
    .btn-text {
      font-size: 28rpx;
      color: #fff;
      font-weight: bold;
    }
  }
  
  .btn-buy {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    
    .btn-text {
      font-size: 28rpx;
      color: #fff;
      font-weight: bold;
    }
  }
}
</style>
